package es.kivitel.android.sms.kernel;

import org.apache.android.mail.GMailSender;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import es.kivitel.android.sms.R;

public class EmailEvent extends Event {	
	public static final String TAG = EmailEvent.class.getName();
	
	public EmailEvent(){
		setComment("standard email");		
		setType(Event.EMAIL_EVENT);
	}
	
	@Override
	public boolean send(Context ctx) {
		switch(getMode()){
			case Event.BACKGROUND_MODE:
				this.sendBackgroundEmail(ctx);
				break;
			case Event.FOREGROUND_MODE:
				sendForegroundEmail(ctx);
				break;
		}
		return false;
	}
	
	public void sendForegroundEmail(Context ctx) {
		Intent sendIntent = new Intent(Intent.ACTION_SEND);
		sendIntent.putExtra(Intent.EXTRA_EMAIL, getDestination());
		sendIntent.putExtra(Intent.EXTRA_SUBJECT, getSubject());
		sendIntent.putExtra(Intent.EXTRA_TEXT, getContent());
		sendIntent.setType("text/plain");
		ctx.startActivity(Intent.createChooser(sendIntent, "MySendMail"));
	}
	
	public void sendBackgroundEmail(Context ctx){
		SharedPreferences sharedPrefs = ctx.getSharedPreferences(
				ctx.getString(R.string.sharedPreferencesFile), 
				Context.MODE_PRIVATE);
		String gmailUser = sharedPrefs.getString(ctx.getString(R.string.gmailUser), "");
		String gmailPass = sharedPrefs.getString(ctx.getString(R.string.gmailPass), "");
		if(gmailUser.length()<6||gmailPass.length()<6){
			Log.e(TAG,"Unable to send any email without the proper gmail user info");
		}
        GMailSender sender = new GMailSender(gmailUser,gmailPass);   
        try {   
            sender.sendMail(this.getSubject(), content, gmailUser, destination);   
        } catch (Exception e) {   
            Log.e(TAG,"Error while sending email in background mode. "+e.getMessage());
            
        }   		  
	}
/*	 
	@Override
	public boolean store(Context ctx) {
		boolean result = false;
		try {
			DatabaseManager.initialize(ctx);
			result = DatabaseManager.execute("INSERT INTO EVT_EVENT (EVT_COMMENT,EVT_START,EVT_CONTENT) VALUES (\""+
					getComment()+"\",,\""+content+"\",\""+subject+"\","+destination+"\")");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	*/
}
